package 多线程;

public class ThreadTest04 {
    public static void main(String[] args) {
        Window1 w1 = new Window1();
        w1.setName("窗口1");
        Window1 w2 = new Window1();
        w2.setName("窗口2");
        Window1 w3 = new Window1();
        w3.setName("窗口3");

        w1.start();
        w2.start();
        w3.start();

    }
}

//创建三个窗口卖票,总票数为100张
class Window1 extends Thread{

    private static int ticket = 100;
    private static Object obj = new Object();

    //使用同步代码块解决继承Thread类的方式的线程安全问题
    @Override
    public void run() {
        //synchronized(this) { 错误的方式,此时的this代表多个对象
        //synchronized(obj) {
        synchronized (Window1.class){ //Window1只会加载一次
            while (true) {
                if (ticket > 0) {
                    System.out.println(Thread.currentThread().getName() + ":卖票,票号为:" + Window1.ticket--);
                } else {
                    break;
                }
            }
        }
    }
}
